<template>
  <div class="datetime-config">
    <h2>{{ $t('system.dateTimeSettings') }}</h2>

    <Card class="box-card" :title="$t('system.manualTimeSetting')">
      <Form :model="timeForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
        <FormItem :label="$t('system.currentTime')">
          <span>{{ currentTime }}</span>
        </FormItem>
        <FormItem :label="$t('system.setTime')">
          <DatePicker
            v-model:value="timeForm.selected_time"
            show-time
            :placeholder="$t('system.selectDateTime')"
            format="YYYY-MM-DD HH:mm:ss"
            :disabled="ntpConfig.enable"
            style="width: 100%;"
          />
        </FormItem>
        <FormItem :label="$t('system.timeZone')">
          <Select
            v-model:value="timeForm.time_zone"
            :disabled="ntpConfig.enable"
            show-search
            :placeholder="$t('system.selectTimeZone')"
            style="width: 100%;"
          >
            <SelectOption v-for="tz in timeZoneOptions" :key="tz.value" :value="tz.value">
              {{ tz.label }}
            </SelectOption>
          </Select>
        </FormItem>
        <FormItem :wrapper-col="{ offset: 6, span: 14 }">
          <Button type="primary" @click="setTimeFunc" :disabled="ntpConfig.enable" style="margin-right: 10px;">{{ $t('common.apply') }}</Button>
          <Button @click="getTimeFunc">{{ $t('common.refresh') }}</Button>
        </FormItem>
      </Form>
    </Card>

    <Card class="box-card" :title="$t('system.ntpSettings')">
      <Form :model="ntpConfig" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
        <FormItem :label="$t('system.enableNTP')">
          <Switch v-model:checked="ntpConfig.enable" @change="handleNtpSwitchChange"/>
        </FormItem>
        <FormItem :label="$t('system.ntpServers')" v-if="ntpConfig.enable">
          <Textarea
            v-model:value="ntpServerInput"
            :rows="3"
            :placeholder="$t('system.ntpServerPlaceholder')"
          />
        </FormItem>
        <FormItem :wrapper-col="{ offset: 6, span: 14 }">
          <Button type="primary" @click="setNTPConfigFunc" style="margin-right: 10px;">{{ $t('common.apply') }}</Button>
          <Button @click="getNTPConfigFunc">{{ $t('common.refresh') }}</Button>
        </FormItem>
      </Form>
    </Card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { message, Card, Form, FormItem, DatePicker, Textarea, Button, Switch, Select, SelectOption } from 'ant-design-vue'
import { useI18n } from 'vue-i18n'
import { getTime, setTime, getNTPConfig, setNTPConfig } from '@/api/system'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import relativeTime from 'dayjs/plugin/relativeTime'

const { t } = useI18n()

const currentTime = ref('')
const currentDayjs = ref(null)
const timerIntervalId = ref(null)

const timeForm = ref({
  selected_time: null,
  time_zone: ''
})
const ntpConfig = ref({
  enable: false,
  servers: []
})

dayjs.extend(utc)
dayjs.extend(relativeTime)

// Define timezone options
const timeZoneOptions = ref([
  { value: 'Etc/GMT+12', label: 'Etc/GMT+12 (UTC-12)' },
  { value: 'Etc/GMT+11', label: 'Etc/GMT+11 (UTC-11)' },
  { value: 'Pacific/Honolulu', label: 'Pacific/Honolulu (UTC-10)' },
  { value: 'America/Anchorage', label: 'America/Anchorage (UTC-9)' },
  { value: 'America/Los_Angeles', label: 'America/Los_Angeles (UTC-8)' },
  { value: 'America/Denver', label: 'America/Denver (UTC-7)' },
  { value: 'America/Chicago', label: 'America/Chicago (UTC-6)' },
  { value: 'America/New_York', label: 'America/New_York (UTC-5)' },
  { value: 'America/Caracas', label: 'America/Caracas (UTC-4)' },
  { value: 'America/Halifax', label: 'America/Halifax (UTC-4)' },
  { value: 'America/Sao_Paulo', label: 'America/Sao_Paulo (UTC-3)' },
  { value: 'America/Argentina/Buenos_Aires', label: 'America/Argentina/Buenos_Aires (UTC-3)' },
  { value: 'Etc/GMT+2', label: 'Etc/GMT+2 (UTC-2)' },
  { value: 'Atlantic/Azores', label: 'Atlantic/Azores (UTC-1)' },
  { value: 'Etc/GMT', label: 'Etc/GMT (UTC+0)' },
  { value: 'Europe/London', label: 'Europe/London (UTC+0)' },
  { value: 'Europe/Berlin', label: 'Europe/Berlin (UTC+1)' },
  { value: 'Europe/Paris', label: 'Europe/Paris (UTC+1)' },
  { value: 'Africa/Cairo', label: 'Africa/Cairo (UTC+2)' },
  { value: 'Europe/Moscow', label: 'Europe/Moscow (UTC+3)' },
  { value: 'Asia/Dubai', label: 'Asia/Dubai (UTC+4)' },
  { value: 'Asia/Karachi', label: 'Asia/Karachi (UTC+5)' },
  { value: 'Asia/Dhaka', label: 'Asia/Dhaka (UTC+6)' },
  { value: 'Asia/Bangkok', label: 'Asia/Bangkok (UTC+7)' },
  { value: 'Asia/Shanghai', label: 'Asia/Shanghai (UTC+8)' },
  { value: 'Asia/Singapore', label: 'Asia/Singapore (UTC+8)' },
  { value: 'Asia/Tokyo', label: 'Asia/Tokyo (UTC+9)' },
  { value: 'Australia/Sydney', label: 'Australia/Sydney (UTC+10)' },
  { value: 'Etc/GMT-11', label: 'Etc/GMT-11 (UTC+11)' },
  { value: 'Pacific/Auckland', label: 'Pacific/Auckland (UTC+12)' },
  { value: 'Etc/GMT-13', label: 'Etc/GMT-13 (UTC+13)' },
])

const ntpServerInput = computed({
  get: () => ntpConfig.value.servers.join('\n'),
  set: (value) => {
    ntpConfig.value.servers = value.split('\n').map(s => s.trim()).filter(s => s)
  }
})

// Function to start the timer
const startTimer = () => {
  clearInterval(timerIntervalId.value);
  if (currentDayjs.value && !ntpConfig.value.enable) {
    timerIntervalId.value = setInterval(() => {
      currentDayjs.value = currentDayjs.value.add(1, 'second');
      currentTime.value = currentDayjs.value.format('YYYY-MM-DD HH:mm:ss');
    }, 1000);
  }
};

const getTimeFunc = async () => {
  try {
    const result = await getTime()
    if (result && result.utc_time) {
      const utcDayjs = dayjs.utc(result.utc_time);
      const localDayjs = utcDayjs.local();

      currentDayjs.value = localDayjs;
      currentTime.value = localDayjs.format('YYYY-MM-DD HH:mm:ss');

      timeForm.value.time_zone = result.time_zone || 'Etc/UTC'
      if (!timeForm.value.selected_time || !timeForm.value.selected_time.isSame(localDayjs)) {
        timeForm.value.selected_time = localDayjs;
      }
      startTimer();
    } else {
      clearInterval(timerIntervalId.value);
      currentDayjs.value = null;
      currentTime.value = t('error.fetchTimeFailed');
    }
  } catch (error) {
    clearInterval(timerIntervalId.value);
    currentDayjs.value = null;
    currentTime.value = t('error.fetchTimeFailed');
    message.error(t('error.fetchTimeFailed') + `: ${error.message}`)
    console.error('Error fetching time:', error.message)
  }
}

const setTimeFunc = async () => {
  try {
    if (!timeForm.value.selected_time) {
      message.warning(t('validation.pleaseSelectDateTime'))
      return
    }

    const utcStringToSend = timeForm.value.selected_time.utc().format('YYYY-MM-DDTHH:mm:ss[Z]');

    const paramsToSend = {
      utc_time: utcStringToSend,
      time_zone: timeForm.value.time_zone
    };

    if (!dayjs(paramsToSend.utc_time, "YYYY-MM-DDTHH:mm:ss[Z]", true).isValid()) {
      message.error(t('error.invalidTimeFormat') + ': ' + paramsToSend.utc_time);
      console.error('Invalid UTC time format before sending:', paramsToSend.utc_time);
      return;
    }

    const result = await setTime(paramsToSend)
    if (result && result.status === 'success') {
      message.success(t('success.setTimeSuccess'))
      getTimeFunc()
    } else {
      message.error(t('error.setTimeFailed') + (result ? ': Unexpected result status' : ''))
      console.error('Unexpected set time result:', result)
    }
  } catch (error) {
    message.error(t('error.setTimeFailed') + `: ${error.message}`)
    console.error('Error setting time:', error.message)
  }
}

const getNTPConfigFunc = async () => {
  try {
    const result = await getNTPConfig()
    ntpConfig.value = result
  } catch (error) {
    message.error(t('error.fetchNTPConfigFailed') + `: ${error.message}`)
    console.error('Error fetching NTP config:', error.message)
  }
}

const setNTPConfigFunc = async () => {
  try {
    const result = await setNTPConfig(ntpConfig.value)
    if (result && result.status === 'success') {
      message.success(t('success.setNTPConfigSuccess'))
      if (result.requires_reboot) {
        message.info(t('info.rebootRequired'))
      }
      if (ntpConfig.value.enable) {
        getTimeFunc()
      }
    } else {
      message.error(t('error.setNTPConfigFailed') + (result ? ': Unexpected result status' : ''))
      console.error('Unexpected set NTP config result:', result)
    }
  } catch (error) {
    message.error(t('error.setNTPConfigFailed') + `: ${error.message}`)
    console.error('Error setting NTP config:', error.message)
  }
}

const handleNtpSwitchChange = (checked) => {
  if (checked) {
    clearInterval(timerIntervalId.value);
  } else {
    getTimeFunc()
  }
}

onMounted(() => {
  getTimeFunc()
  getNTPConfigFunc()
})

onUnmounted(() => {
  clearInterval(timerIntervalId.value);
})

</script>

<style scoped>
.datetime-config {
  padding: 20px;
}
.box-card {
  margin-bottom: 20px;
}
:deep(.ant-form-item-label) {
}
</style>